<template>
  <div>
    <el-dialog :visible="dialogVisible" :title="title" :before-close="handleClose" center width="400px">
      <el-form ref="editFormRef" :model="editForm" :rules="rules" size="small">

        <el-form-item label="设备类型编号" :label-width="labelWidth" prop="typeNumber" class="line">
              <el-input
              :disabled="isEdit"
              class="selectCss"
              placeholder="请输入设备类型编号"
              v-model="editForm.typeNumber"></el-input>
            </el-form-item>

        <el-form-item label="设备类型名称" :label-width="labelWidth" prop="typeName" class="line">
          <el-input v-model="editForm.typeName" @input="labelNameLongFn" placeholder="请输入设备类型名称"></el-input>
        </el-form-item>

        <el-form-item label="设备类型等级" :label-width="labelWidth" prop="typeLevel" class="line">
          <el-select class="selectCss"
          :disabled="isEdit"
          @change="changeType"
          v-model="editForm.typeLevel"
          placeholder="请选择设备类型等级">
            <el-option label='一级' value="1"></el-option>
            <el-option label='二级' value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备上级类型" :label-width="labelWidth" prop="typeParentId" class="line">
          <!-- <el-input v-model="editForm.eqptTypeParentId"  placeholder="请选择上级类型"></el-input> -->
          <el-select class="selectCss"
          :disabled="isChild"
          v-model="editForm.typeParentId"
          placeholder="请选择设备上级类型">
            <el-option
              v-for="item in parentTypeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            ></el-option>
                <!-- <el-option value="一级">二级</el-option> -->
              </el-select>
        </el-form-item>

        <el-form-item label="图片" prop="mapUrl" style="margin-left: 15px">
          <el-upload
            class="avatar-uploader"
            action=""
            :auto-upload="true"
            :show-file-list="false"
            :http-request="handleUpload"
            accept=".jpg, .jpeg, .png, .bmp"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="editForm.mapUrl" :src="editForm.mapUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleOk('editFormRef')">确 定</el-button>
      </div>
    </el-dialog>

    <type-modal ref="typeModal"></type-modal>
  </div>
</template>

<script>
// import pick from 'lodash.pick'
import { saveDeviceType, getDeviceTypeList, uploadImage, getImgSource } from '@/views/children/safety/js/device'
import TypeModal from './TypeModal'
import { sourceFlag } from '@/views/children/dcenter/js/constants'

export default {
  name: 'DeviceCategoryModal',
  components: { TypeModal },
  data () {
    return {
      dialogVisible: false,
      model: {},
      title: '添加类型',
      labelWidth: '120px',
      isEdit: false,
      isChild: false,
      parentTypeList: [], // 父类型列表
      editForm: {
        typeNumber: '',
        typeName: '',
        typeLevel: '',
        typeParentId: '',
        mapUrl: ''
      },
      imgUrl: '',
      rules: {
        typeNumber: [{ required: true, message: '请输入设备类型编号!' }],
        typeName: [{ required: true, message: '请输入设备类型名称!' }],
        typeLevel: [{ required: true, message: '请选择设备类型等级!' }],
        typeParentId: [{ required: true, message: '请选择设备上级类型!' }],
        mapUrl: [{ required: true, message: '请上传图片!' }]
      },
      sourceFlag
    }
  },
  props: {
    // judgeId: {
    //   type: String,
    //   required: true
    // },
    checkList: {
      type: Array,
      required: false,
      default: () => []
    },
    deviceTypeList: {
      type: Array,
      required: false,
      default: () => []
    }
  },
  methods: {
    add () {
      this.edit({})
    },

    // 编辑
    edit (record) {
      this.dialogVisible = true
      this.model = Object.assign({}, record)
      if (record.typeId) {
        console.log(record)
        this.getParentType()
        this.title = '编辑类型'
        this.isEdit = true
        this.rules.typeParentId[0].required = false

        this.editForm = {
          ...record,
          typeLevel: record.typeLevel === '一级' ? '1' : '2',
          typeParentId: record.typeParentId === '0' ? '' : record.typeParentId
        }
        this.imgUrl = record.mapUrl
        if (this.imgUrl) {
          this.getImg(this.imgUrl)
        }
        if (this.editForm.typeLevel === '1') {
          this.isChild = true
        }
        console.log(record)
      }
    },
    // 展示图片
    async getImg (data) {
      let res = await getImgSource(data)
      let blob = new Blob([res], {
        type: res.type
      })
      let url = window.URL.createObjectURL(blob)
      this.editForm.mapUrl = url
    },

    labelNameLongFn () {
      let { typeName } = this.editForm
      if (!typeName) return
      let res = this.inputLength(this.editForm.typeName)
      if (typeof res === 'object') {
        // 长度大于30，且记录了当前的下标
        this.$message.warning('长度不能超过30个字符！')
        // this.isLong++
        this.editForm.typeName = typeName.slice(0, res.index)
      }
    },
    // 计算input长度
    inputLength (val) {
      var len = 0
      for (var i = 0; i < val.length; i++) {
        var a = val.charAt(i)
        if (a.match(/[^\x0-\xff]/ig) != null) {
          if (len >= 29) return { len, index: i }
          len += 2
        } else {
          if (len >= 30) return { len, index: i }
          len += 1
        }
      }
      return len
    },
    // 上传限制
    handleUpload (res) {
      let uploadFileObj = res.file
      this.fileUploadFun(uploadFileObj)
    },
    beforeAvatarUpload (file) {
      let typeArr = ['image/jpeg', 'image/png', 'image/jpg', 'image/bmp']
      const isJPG = typeArr.includes(file.type)
      // const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/JPEG/PNG/BMP 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return isJPG && isLt2M
    },
    // 上传文件
    async fileUploadFun (fileObj) {
      let param = new FormData()
      param.append('file', fileObj)
      const { code, data } = await uploadImage(param)
      if (code === 0) {
        try {
          const resImg = await getImgSource(data)
          let blob = new Blob([resImg], {
            type: resImg.type
          })
          let url = window.URL.createObjectURL(blob)
          this.editForm.mapUrl = url
          this.imgUrl = data
          // console.log(this.editForm.mapUrl)
        } catch (e) {
          this.$message.warning('上传失败！')
        }
        this.$message.success('上传成功')
      } else {
        this.$message.warning('上传失败！')
      }
    },
    // 提交表单
    handleOk (editFormRef) {
      this.$refs[editFormRef].validate(async valid => {
        if (valid) {
          let res
          let query = {
            ...this.editForm,
            mapUrl: this.imgUrl
          }
          delete query.childEqptTypeList
          delete query.typeParentName
          res = await saveDeviceType(query)
          if (res.code === 0) {
            console.log(res.data)
            this.$refs.editFormRef.resetFields()
            this.$emit('ok')
            this.$parent.dialogVisible = false
          } else {
            this.$message.error(res.msg)
          }
        }
      })
    },

    async changeType () {
      let { typeLevel } = this.editForm
      if (typeLevel === '1') {
        // 如果选择为1级，没有父类型 父类型选择框为disabled
        this.rules.typeParentId[0].required = false
        this.isChild = true
      } else {
        // 如果为2级，获取父类型列表
        this.rules.typeParentId[0].required = true
        this.isChild = false
        this.getParentType()
      }
    },
    // 获取一级类型（父类型列表）
    async getParentType () {
      try {
        let query = {
          typeLevel: '1'
        }
        let res = await getDeviceTypeList(query)
        if (res.code === 0) {
          this.parentTypeList = res.data
        } else {
          this.$message.error(res.msg)
        }
      } catch (e) {}
    },

    // 取消
    handleCancel () {
      this.$parent.dialogVisible = false
      this.$refs.editFormRef.resetFields()
    },
    handleClose () {
      this.handleCancel()
    }
  }
}
</script>

<style lang="scss" scoped>
.line{
  display: inline-block;
  width: 350px;
}
.selectCss {
  width: 230px;
}
.avatar-uploader /deep/ {
  line-height: 1;
  .el-upload {
    box-sizing: border-box;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
}
</style>
